﻿using System;
using System.Collections.Specialized;
using System.Web.UI;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using FamilyTreeProject.Common;
using FamilyTreeProject.DotNetNuke.Module.Common;
using FamilyTreeProject.DotNetNuke.Module.Presenters;

namespace FamilyTreeProject.DotNetNuke.Module.Views
{
    public class EditIndividualView : FamilyTreeControlBase, 
        IEditIndividualView,
        IPostBackDataHandler,
        IPostBackEventHandler
    {
        #region Protected Members

        protected EditIndividualPresenter presenter;

        #endregion

        #region Constructors

        /// <summary>
        /// Constructs an EditIndividualView
        /// </summary>
        public EditIndividualView()
        {
            presenter = new EditIndividualPresenter(this, Util.GetIndividualsService());
        }

        #endregion

        #region IEditIndividualView Members

        /// <summary>
        /// Gets or Sets the First Name of the Individual
        /// </summary>
        public string FirstName { get; set; }

        /// <summary>
        /// Gets the Id of the Individual
        /// </summary>
        public int IndividualId
        {
            get
            {
                int individualId = Null.NullInteger;
                if (Page.Request.Params["Id"] != null)
                    individualId = Int32.Parse(Page.Request.Params["Id"]);
                return individualId;
            }
        }

        /// <summary>
        /// Gets and Sets whether the Voew is in Add mode
        /// </summary>
        public bool IsAddMode { get; set; }

        /// <summary>
        /// Sets the Last Name of the Individual
        /// </summary>
        public string LastName { get; set; }

        /// <summary>
        /// Gets or Sets the Message
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// Gets the Id of the Module
        /// </summary>
        public int ModuleId
        {
            get { return ModuleContext.ModuleId; }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// RenderButtons renders the Command Buttons
        /// </summary>
        /// <param name="writer">An HtmlTextWriter</param>
        private void RenderButtons(HtmlTextWriter writer)
        {
            //Render start of row
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            //Render start of Button cell
            writer.AddAttribute(HtmlTextWriterAttribute.Colspan, "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);

            //Render Save Button
            writer.WriteCommandButton(Page.ClientScript.GetPostBackClientHyperlink(this, Constants.ACTION_Save),
                                      ResolveUrl(Constants.IMAGE_Save),
                                      LocalizeString(Constants.KEY_SaveIndividual));

            writer.WriteSpace(2);

            //Render Delete Button
            if (!IsAddMode)
            {
                writer.WriteCommandButton(Page.ClientScript.GetPostBackClientHyperlink(this,Constants.ACTION_Delete),
                                          ResolveUrl(Constants.IMAGE_Delete),
                                          LocalizeString(Constants.KEY_DeleteIndividual));

                writer.WriteSpace(2);
            }

            //Render Cancel Button
            writer.WriteCommandButton(Globals.NavigateURL(),
                                      ResolveUrl(Constants.IMAGE_Cancel),
                                      LocalizeString(Constants.KEY_ReturnToList));

            //Render end of Button cell
            writer.RenderEndTag();

            //Render end of row
            writer.RenderEndTag();
        }

        /// <summary>
        /// Renders a single field
        /// </summary>
        /// <param name="writer">The HtmlTextWriter to use</param>
        /// <param name="labelKey">A reosurcekey for the Field Label</param>
        /// <param name="value">The Field Value</param>
        private void RenderField(HtmlTextWriter writer, string labelKey, string value)
        {
            //Render start of row
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);

            //Render Label Cell
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(LocalizeString(labelKey));
            writer.RenderEndTag();

            //Render start of Field Cell
            writer.RenderBeginTag(HtmlTextWriterTag.Td);

            //Render Field as Text Box
            writer.AddAttribute(HtmlTextWriterAttribute.Value, value);
            writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID + ":" + labelKey);
            writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID + ClientIDSeparator + labelKey);
            writer.RenderBeginTag(HtmlTextWriterTag.Input);
            writer.RenderEndTag();

            //Render end of Field Cell
            writer.RenderEndTag();

            //Render end of row
            writer.RenderEndTag();      
        }

    	#endregion        
 
        #region Protected Methods

        /// <summary>
        /// OnInit runs when the Control is initialised
        /// </summary>
        /// <param name="e">An EventArgs object</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ID = "EditIndividual";
        }

        /// <summary>
        /// OnLoad runs when the Control is loaded.  It calls the Presenters OnViewLoaded method
        /// </summary>
        /// <param name="e">An EventArgs object</param>
        protected override void OnLoad(EventArgs e)
        {
            presenter.OnViewLoaded(Page.IsPostBack);
        }

        /// <summary>
        /// OnPreRender runs just prior to the control being rendered
        /// </summary>
        /// <param name="e">An EventArgs object</param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            Page.RegisterRequiresPostBack(this);
        }

        /// <summary>
        /// Render the Control
        /// </summary>
        /// <param name="writer">An HtmlTextWriter</param>
        protected override void Render(HtmlTextWriter writer)
        {
            //Render Message
            if (!String.IsNullOrEmpty(Message))
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, Constants.STYLE_ErrorMessage);
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                writer.Write(LocalizeString(Message));
                writer.RenderEndTag();
            }

            //Render Header Tag
            if (!IsAddMode)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.H2);
                writer.Write(FirstName + "&nbsp;" + LastName);
                writer.RenderEndTag();

            }

            //Render Start of Table
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            //Render Start of Table Body
            writer.RenderBeginTag(HtmlTextWriterTag.Tbody);

            //Render FirstName
            RenderField(writer, Constants.KEY_FirstName, FirstName);

            //Render LastName
            RenderField(writer, Constants.KEY_LastName, LastName);

            //Render CommandButtons
            RenderButtons(writer);

            //Render End of Table Body
            writer.RenderEndTag();

            //Render End of Table
            writer.RenderEndTag();
        }

        #endregion

        #region IPostBackDataHandler Members

        /// <summary>
        /// LoadPostData loads the Form data into the proeprties
        /// </summary>
        /// <param name="postDataKey">The key used to identify this control</param>
        /// <param name="postCollection">The collection of form data posted back to the server</param>
        /// <returns>A boolean</returns>
		public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
        {
            FirstName = postCollection[postDataKey + ":" + Constants.KEY_FirstName];
            LastName = postCollection[postDataKey + ":" + Constants.KEY_LastName];

		    return false;
        }

        /// <summary>
        /// Can be used to raise an event when the Postback data is different from the original data
        /// </summary>
        /// <remarks>Not used</remarks>
        public void RaisePostDataChangedEvent() { }

    	#endregion        
        
        #region IPostBackEventHandler Members

        /// <summary>
        /// Raise an event when a button on the form is clicked
        /// </summary>
        /// <param name="eventArgument">The argument of the button making the postback</param>
        public void RaisePostBackEvent(string eventArgument)
        {
            switch (eventArgument)
            {
                case Constants.ACTION_Save:
                     if (presenter.OnSave())
                         Page.Response.Redirect(Globals.NavigateURL());
                    break;
                case Constants.ACTION_Delete:
                    if (presenter.OnDelete())
                        Page.Response.Redirect(Globals.NavigateURL());
                    break;
                default:
                    break;
            }
        } 

        #endregion
    }
}
